package com.shujia.Dao;

import com.shujia.JdbcUtil.JdbcUitl;
import com.shujia.user.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class userDao {
    /**
     * 查询
     * @param
     * @return user对象
     */
    public User loginon(String username){
        User user = null;
        Connection conn=null;
        try {
            conn = JdbcUitl.getConnection();
            PreparedStatement ps = conn.prepareStatement("select * from user where username=?");
            ps.setString(1,username);
            ResultSet r = ps.executeQuery();
            if(r.next()){
                int id = r.getInt("id");
                String username1 = r.getString("username");
                String password = r.getString("password");
                user = new User(id, username, password);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user;

    }

    /**
     * 插入
     * @return int
     */
    public int insertuer(User uesr){
        int i=0;
        Connection con;
        try {
            con = JdbcUitl.getConnection();
            PreparedStatement ps = con.prepareStatement("insert into user(username,password) values(?,?)");
            ps.setString(1,uesr.getUsername());
            ps.setString(2,uesr.getPassword());
            i = ps.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return i;
    }

    /**
     * 修改
     * @return
     */
    public int update(String username,String newpassword){
        Connection conn = null;
        int i=0;

        try {
            conn = JdbcUitl.getConnection();
            PreparedStatement ps = conn.prepareStatement("update user set password=? where username=?");
            ps.setString(1,newpassword);
            ps.setString(2,username);
            i = ps.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return i;
    }

}
